package com.ccrfid.rmc6.service.poi;

import com.ccrfid.rmc6.appconfig.exception.pojo.AppException;
import com.ccrfid.rmc6.appconfig.exception.pojo.CustomErrors;
import com.ccrfid.rmc6.entity.poi.PoiLineEntity;
import com.ccrfid.rmc6.repository.poi.PoiLineRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import javax.ws.rs.core.Response;
import java.util.List;

@Service
@Transactional
public class PoiLineServiceImpl implements PoiLineService {
    private static final Logger logger = LoggerFactory.getLogger(PoiLineServiceImpl.class);

    @Autowired
    private PoiLineRepository poiLineRepository;

    @Override
    public List<PoiLineEntity> getAllLines(Integer floorNumber) {
        if (floorNumber != null) {
            return poiLineRepository.getAllByFloorNumber(floorNumber);
        } else {
            return poiLineRepository.getAllBy();
        }
    }

    @Override
    public PoiLineEntity getLineById(Long id) throws AppException {
        if (!poiLineRepository.existsById(id)) {
            throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(),
                    CustomErrors.resource_not_found.getCode(), CustomErrors.resource_not_found.getReason(), "");
        }
        return poiLineRepository.getById(id);
    }

    @Override
    public PoiLineEntity createLine(PoiLineEntity entity) throws AppException {
        if (entity == null || entity.getLine() == null) {
            throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(),
                    CustomErrors.param_is_null.getCode(), CustomErrors.param_is_null.getReason(), "");
        }
        entity.setId(null);
        return poiLineRepository.save(entity);
    }

    @Override
    public PoiLineEntity updateLine(Long id, PoiLineEntity entity) throws AppException {
        if (!poiLineRepository.existsById(id)) {
            throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(),
                    CustomErrors.resource_not_found.getCode(), CustomErrors.resource_not_found.getReason(), "");
        }
        if (entity == null || entity.getLine() == null) {
            throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(),
                    CustomErrors.param_is_null.getCode(), CustomErrors.param_is_null.getReason(), "");
        }
        entity.setId(id);
        return poiLineRepository.save(entity);
    }

    @Override
    public boolean deleteLineById(Long id) throws AppException {
        if (!poiLineRepository.existsById(id)) {
            throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(),
                    CustomErrors.resource_not_found.getCode(), CustomErrors.resource_not_found.getReason(), "");
        }
        poiLineRepository.deleteById(id);
        return true;
    }
}
